const koa = require('koa')
const koaBody = require('koa-body')
const cors = require('koa-cors')
const error = require('koa-json-error')
const parameter = require('koa-parameter')
const mongoose = require('mongoose')
const morgan = require('koa-morgan')
const koaStatic = require('koa-static')
const { limitFlow } = require('./middleware/index')
const app = new koa()
const path = require('path')
const fs = require('fs')
const routing = require('./routes/index')
const { mgdb } = require('./config/index')
const ENV = process.env.NODE_ENV
console.log('数据库地址：',mgdb.url)
//链接mongoDB
mongoose.connect(mgdb.url, mgdb.options, () => {
  console.log('MongoDB success')
})
mongoose.connection.on('error', console.error)

//日志
if (ENV === 'production') {
  const logFile = path.join(__dirname, 'logs', 'access.log')
  let writeStream = fs.createWriteStream(logFile, {
    flags: 'a'
  })
  app.use(morgan('combined', {
    stream: writeStream //写入文件流
  }))
} else {
  //访问打印
  app.use(morgan('dev'))
  //允许跨域 开发环境
  app.use(cors())
}
//错误处理
app.use(error({
  postFormat: (e, { stack, ...rest }) => ENV === 'production' ? rest : { stack, ...rest }
}))
app.use(limitFlow)
//接收文件数据
app.use(koaBody({
  multipart: true, //是否接受Form表单格式的文件数据
  // formidable: {
  //     uploadDir: path.join(__dirname, 'public'), // 文件上传目录
  //     keepExtensions: true, // 保留文件扩展名
  // },
}))
//文件静态服务
app.use(koaStatic(path.join(__dirname, 'public')))
//校检参数
app.use(parameter(app))
//注册路由
routing(app)

app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
})

module.exports = app
